package com.shouyun.modules.oss.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.shouyun.common.exception.ShouYunException;
import com.shouyun.common.utils.DataUtils;
import com.shouyun.modules.oss.service.OssService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class OssServiceImpl implements OssService {

    @Override
    public String getWorkspaceAndPath(String path) {
        //获取参数
        JSONObject sysParams = DataUtils.getData(DataUtils.PARAMS, "sys");
        String workspace = sysParams.getString("workspace");
        if (StringUtils.isBlank(workspace)) {
            throw new ShouYunException("请先配置工作空间");
        }
        if (StringUtils.isNotBlank(path) && path.substring(0, 1) != "\\") {
            path = "\\" + path;
        }
        if (StringUtils.isNotBlank(path)) {
            workspace += path;
        }
        return workspace;
    }

    @Override
    public void download(File file, HttpServletResponse response) {
        if (!file.exists()) {
            return;
        }
        InputStream is = null;
        try {
            response.reset();
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("utf-8"), "ISO8859-1"));

            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream;charset=UTF-8");
            is = new FileInputStream(file);     //是文件而不是文件名。
            FileCopyUtils.copy(is, response.getOutputStream());//将文件写到输出流中
        } catch (Exception e) {
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}